<?php
namespace App\Service\Admin;

use Illuminate\Support\Facades\DB;

class UserService extends BaseService
{
    //用户

    protected $autoTypes = [
        '普通会员', '黄金/铂金/钻石【手动】', '黄金/铂金/钻石【自动】', 'SVIP【手动】',
    ];

    //选项
    public function getOption()
    {
        //$arys['level'][] = ['id' => 0, 'type' => 1, 'title' => '普通会员'];
        $arys['level'] = [];
        $res = $this->dbConn($this->dbUlevel)->where('del', 0)->get();
        if (count($res)) {
            foreach ($res as $v) {
                $v = (array) $v;
                $arys['level'][] = [
                    'id' => $v['id'],
                    'type' => $v['type'],
                    'title' => $v['title'].'-'.$v['ver'],
                ];
            }
        }
        return $arys;
    }

    public function del($id){
        $db = DB::table($this->dbUser)->where('id', $id)->first();
        if (empty($db)) {
            return array('code' => -2, 'msg' => '用户不存在');
        }
        $res = DB::table($this->dbUser)->where('id', $id)->update(['del' => 1]);
        if ($res) {
            return array('code' => 0, 'msg' => '删除成功');
        } else {
            return array('code' => -1, 'msg' => '删除失败');
        }
    }
    /**
     * 用户列表
     * @param array $pages【start，limit】
     */
    public function getUserList($pages, $pas)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = DB::table($this->dbUser)->where('del', 0);
        if ($pas['nick']) {
            $db = $db->where('nickname', 'like', '%'.$pas['nick'].'%');
        }
        if ($pas['phone']) {
            $db = $db->where('phone', 'like', '%'.$pas['phone'].'%');
        }
        if ($pas['level']) {
            $db = $db->where('level_id', $pas['level']);
        }
        if ($pas['id']) {
            $db = $db->where('id', $pas['id']);
        }
        if ($pas['serial']) {
            $db = $db->where('serial', $pas['serial']);
        }
        $total = $db->count();
        $res = $db->orderBy('id', 'desc')
            ->skip($start)->take($pages['limit'])->get();
        if (!count($res)) {
            return array('code' => -2, 'msg' => '没有用户');
        }
        $autoTypes = $this->autoTypes;
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $head = file_exists($v['avatarUrl']) ? $v['avatarUrl'] : '';
            $levelOne = (array) $this->dbConn($this->dbUlevel)
                ->where('del', 0)
                ->where('id', $v['level_id'])
                ->first();
            $readNum = $this->dbConn($this->dbUtrace)->where('uid', $v['id'])->count();
//            $addressNum = $this->dbConn($this->dbUaddress)->where('uid', $v['id'])->count();
            $couponNum = $this->dbConn($this->dbUcoupon)->where('uid', $v['id'])->count();
            $payNum = $this->dbConn($this->dbPay)
                ->where('uid', $v['id'])
                ->where('type', 1)
                ->where('status', 2)
                ->count();
            $tname = '普通会员';
//            $tname = array_key_exists($v['is_auto'], $autoTypes) ? $autoTypes[$v['is_auto']] : '';
            if ($v['is_auto'] == 3) {
                $tname = 'SVIP会员<br>';
                $tname .= '【手动】<br>';
                $tname .= $v['discount'].'%';
            } else if (in_array($v['is_auto'], [1, 2])) {
                if (!empty($levelOne)) {
                    $tname = $levelOne['title'].'<br>【';
                    $tname .= $v['is_auto']==1 ? '手动' : '自动';
                    $tname .= '】<br>';
                    $tname .= $levelOne['discount'].'%';
                }
            }
            $dzOne = (array) $this->dbConn($this->dbUaddress)->where('del', 0)
                ->where('uid', $v['id'])
                ->orderBy('id', 'asc')
                ->first();
            $addressNum = !empty($dzOne)&&$dzOne['wx_name'] ? $dzOne['wx_name'] : '-';
            $arys[] = [
                'id' => $v['id'],
                'serial' => $v['serial'] ? $v['serial'] : '-',
                'phone' => $v['phone'] ? $v['phone'] : '-',
                'nickname' => $v['nickname'],
                'prefix' => env('DOMAIN') . '/',
                'avatarUrl' => $head,
                'lasttime' => $v['lasttime'],
                'balance' => $v['balance'] / 100,
                'level_id' => $v['level_id'],
                'levelName' => $tname,
                'is_auto' => $v['is_auto'],
                'discount' => $v['discount'],
                'readNum' => $readNum,
                'addressNum' => $addressNum,
                'couponNum' => $couponNum,
                'rechargeNum' => $payNum,
            ];
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $arys, 'total' => $total);
    }

    /**
     * 用户列表
     */
    public function getUlist($pas)
    {
        $db = DB::table($this->dbUser);
        if ($pas['nick']) {
            $db = $db->where('nickname', 'like', '%'.$pas['nick'].'%');
        }
        if ($pas['phone']) {
            $db = $db->where('phone', 'like', '%'.$pas['phone'].'%');
        }
        $res = $db->orderBy('id', 'desc')->get();
        if (!count($res)) {
            return array('code' => -2, 'msg' => '没有用户');
        }
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $head = file_exists($v['avatarUrl']) ? $v['avatarUrl'] : '';
            $levelOne = (array) $this->dbConn($this->dbUlevel)->where('id', $v['level_id'])->first();
            $readNum = $this->dbConn($this->dbUtrace)->where('uid', $v['id'])->count();
            $addressNum = $this->dbConn($this->dbUaddress)->where('uid', $v['id'])->count();
            $couponNum = $this->dbConn($this->dbUcoupon)->where('uid', $v['id'])->count();
            $payNum = $this->dbConn($this->dbPay)
                ->where('uid', $v['id'])
                ->where('type', 1)
                ->where('status', 2)
                ->count();
            $arys[] = [
                'id' => $v['id'],
                'serial' => $v['serial'] ? $v['serial'] : '-',
                'phone' => $v['phone'] ? $v['phone'] : '-',
                'nickname' => $v['nickname'],
                'prefix' => env('DOMAIN') . '/',
                'avatarUrl' => $head,
                'lasttime' => $v['lasttime'],
                'balance' => $v['balance'] / 100,
                'levelName' => empty($levelOne) ? '-' : $levelOne['title'],
                'discount' => $v['discount'],
                'readNum' => $readNum,
                'addressNum' => $addressNum,
                'couponNum' => $couponNum,
                'rechargeNum' => $payNum,
            ];
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $arys);
    }

    /**
     * 浏览历史
     * @param array $pages【start，limit】
     */
    public function getTraceList($pages, $uid)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = DB::table($this->dbUtrace);
        if ($uid) {
            $db = $db->where('uid', $uid);
        }
        $total = $db->count();
        $res = $db->orderBy('id', 'desc')
            ->skip($start)->take($pages['limit'])
            ->get();
        if (!count($res)) {
            return array('code' => -2, 'msg' => '没有历史');
        }
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $uname = '';
            $gname = '';
            $gimg = '';
            //用户信息
            $uOne = (array) DB::table($this->dbUser)->where('id', $v['uid'])->first();
            if (!empty($uOne)) {
                $uname = $uOne['nickname'];
            }
            //商品信息
            $gOne = (array) DB::table($this->dbGoods)->where('id', $v['gid'])->first();
            if (!empty($gOne)) {
                $gname = $gOne['title'];
                $gimg = env('DOMAIN') . '/' . $gOne['bigimg'];
            }
            $arys[] = [
                'id' => $v['id'],
                'uname' => $uname,
                'gname' => $gname,
                'gimg' => $gimg,
                'addtime' => $v['addtime'],
            ];
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $arys, 'total' => $total);
    }

    /**
     * 收货地址
     * @param array $pages【start，limit】
     */
    public function getAddressList($pages, $uid)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = DB::table($this->dbUaddress)->where('del', 0);
        if ($uid) {
            $db = $db->where('uid', $uid);
        }
        $total = $db->count();
        $res = $db->orderBy('id', 'desc')
            ->skip($start)->take($pages['limit'])
            ->get();
        if (!count($res)) {
            return array('code' => -2, 'msg' => '没有地址');
        }
        $types = $this->addressTypes;
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $uname = '';
            //用户信息
            $uOne = (array) DB::table($this->dbUser)->where('id', $v['uid'])->first();
            if (!empty($uOne)) {
                $uname = $uOne['nickname'];
            }
            $tname = array_key_exists($v['type'], $types) ? $types[$v['type']] : '';
            $arys[] = [
                'id' => $v['id'],
                'uid' => $v['uid'],
                'uname' => $uname,
                'accepter' => $v['accepter'],
                'phone' => $v['phone'],
                'type' => $v['type'],
                'type_name' => $tname,
                'wx_name' => $v['wx_name'],
                'wx_door' => $v['wx_door'],
                'wx_map' => $v['wx_map'],
                'door' => $v['door'],
                'selected' => $v['selected'],
                'addtime' => $v['addtime'],
            ];
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $arys, 'total' => $total);
    }

    /**
     * 设置收货地址默认
     * @param int $id
     */
    public function setAddressDefault($id)
    {
        $res = (array) DB::table($this->dbUaddress)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return array('code' => -2, 'msg' => '地址不存在');
        }
        //取消其他的默认
        DB::table($this->dbUaddress)
            ->where('uid', $res['uid'])
            ->where('id', '<>', $id)
            ->update(['selected' => 0, 'seltime' => toDate()]);
        //设置默认
        DB::table($this->dbUaddress)
            ->where('id', $id)
            ->update(['selected' => 1, 'seltime' => toDate()]);
        return array('code' => 0, 'msg' => 'success');
    }

    /**
     * 用户充值记录
     * @param  int $uid
     * @param array $pages【start，limit】
     */
    public function getRechargeIndex($uid, $pages)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = DB::table($this->dbPay)->where('uid', $uid)
            ->where('type', 1)
            ->where('status', 2);
        $total = $db->count();
        $res = $db->orderBy('id', 'desc')
            ->skip($start)->take($pages['limit'])
            ->get();
        if (!count($res)) {
            return array('code' => -2, 'msg' => '没有记录');
        }
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $arys[] = [
                'id' => $v['id'],
                'tname' => '余额充值',
                'money' => toNumber($v['money']),
                'addtime' => $v['addtime'],
            ];
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $arys, 'total' => $total);
    }

    /**
     * 礼品卡兑换记录
     * @param  int $uid
     * @param array $pages【start，limit】
     */
    public function getCardIndex($uid, $pages)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = $this->dbConn($this->dbCardUser)
            ->where('uid', $uid)
            ->where('del', 0)
            ->where('uid', $uid)
            ->where('is_used', 1);
        $total = $db->count();
        $res = $db->orderBy('id', 'desc')
            ->skip($start)->take($pages['limit'])
            ->get();
        if (!count($res)) {
            return array('code' => -2, 'msg' => '没有记录');
        }
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $arys[] = [
                'id' => $v['id'],
                'tname' => '礼品卡',
                'money' => toNumber($v['price']),
                'addtime' => $v['addtime'],
            ];
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $arys, 'total' => $total);
    }

    /**
     * 用户提现记录
     * @param  int $uid
     * @param array $pages【start，limit】
     */
    public function getTixianIndex($uid, $pages)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = DB::table($this->dbTixian)->where('uid', $uid)
            ->where('status', 2);
        $total = $db->count();
        $res = $db->orderBy('id', 'desc')
            ->skip($start)->take($pages['limit'])
            ->get();
        if (!count($res)) {
            return array('code' => -2, 'msg' => '没有记录');
        }
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $arys[] = [
                'id' => $v['id'],
                'money' => $v['amount'] / 100,
                'addtime' => $v['addtime'],
            ];
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $arys, 'total' => $total);
    }

    /**
     * 用户消费统计
     * @param  int $uid
     * @param array $pages【start，limit】
     */
    public function getOrderIndex($uid, $pages)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = DB::table($this->dbOrder)->where('uid', $uid)
            ->where('status', 4);
        $total = $db->count();
        $res = $db->orderBy('id', 'desc')
            ->skip($start)->take($pages['limit'])
            ->get();
        if (!count($res)) {
            return array('code' => -2, 'msg' => '没有记录');
        }
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $gname = ''; $sku_name = '';
            $skuOnes = $this->dbConn($this->dbOsku)->where('order_id', $v['id'])->get();
            if (count($skuOnes)) {
                foreach ($skuOnes as $vv) {
                    $vv = (array) $vv;
                    if ($gname != '') {
                        $gname .= '<br/>';
                    }
                    if ($sku_name != '') {
                        $sku_name .= '<br/>';
                    }
                    $gname .= $vv['gname'];
                    $sku_name .= $vv['sku_name'].' * '.$vv['num'];
                }
            }
            $arys[] = [
                'id' => $v['id'],
                'gname' => $gname,
                'sku_name' => $sku_name,
                'addtime' => $v['addtime'],
                'real_pay' => toNumber($v['real_pay']),
                'pay_way' => $v['pay_way']==1 ? '微信支付' : '余额支付',
            ];
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $arys, 'total' => $total);
    }

//    /**
//     * 设置折扣率
//     * @param int $uid
//     * @param string $ln
//     * @param int $discount
//     */
//    public function setVip($uid, $ln, $discount)
//    {
//        $uOne = (array) $this->dbConn($this->dbUser)
//            ->where('del', 0)
//            ->where('id', $uid)
//            ->first();
//        if (empty($uOne)) {
//            return $this->toback(-2, '该用户不存在');
//        }
//        $levelOne = (array) $this->dbConn($this->dbUlevel)
//            ->where('del', 0)
//            ->where('title', $ln)
//            ->first();
//        if (empty($levelOne)) {
//            return $this->toback(-2, '该等级不存在');
//        }
//        $this->dbConn($this->dbUser)->where('id', $uid)->update([
//            'level_id' => $levelOne['id'], 'discount' => $discount,
//        ]);
//        return $this->toback();
//    }

    /**
     * 设置折扣率
     * @param int $uid
     * @param array $pas【is_auto，discount，level_id】
     */
    public function setVip($uid, $pas)
    {
        $uOne = (array) $this->dbConn($this->dbUser)
            ->where('del', 0)
            ->where('id', $uid)
            ->first();
        if (empty($uOne)) {
            return $this->toback(-2, '该用户不存在');
        }
        $this->dbConn($this->dbUser)->where('id', $uid)->update($pas);
        //变为自动后，检测等级情况
        if ($pas['is_auto'] == 2) {
            $uCost = $uOne['real_cost']; //用户累计订单消费
            $uLevelId = $uOne['level_id'];
            $levelNew = (array) $this->dbConn($this->dbUlevel)
                ->where('del', 0)
                ->where('type', 1)
                ->where('real_cost', '<=', $uCost)
                ->orderBy('real_cost', 'desc')
                ->first();
            if (!empty($levelNew) && $levelNew['id'] != $uLevelId) {
                $this->dbConn($this->dbUser)->where('id', $uid)
                    ->update(['level_id' => $levelNew['id'], 'is_auto' => 2]);
            }
        }
        return $this->toback();
    }

    //卡号列表
    public function bankList($pages, $uid)
    {
        $this->bankDefaultInit($uid);
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = $this->dbConn($this->dbUserWithdrawInfo)
            ->where('del', 0)
            ->where('uid', $uid);
        $total = $db->count();
        $res = $db->skip($start)->take($pages['limit'])
            ->orderBy('id', 'desc')
            ->get();
        if (!count($res)) {
            return $this->toback(-2, '没有记录');
        }
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $uOne = (array) $this->dbConn($this->dbUser)
                ->where('del', 0)
                ->where('id', $v['uid'])
                ->first();
            $uname = !empty($uOne)&&$uOne['nickname'] ? $uOne['nickname'] : '-';
            $arys[] = [
                'id' => $v['id'],
                'uid' => $v['uid'],
                'uname' => $uname,
                'realname' => $v['name'],
                'phone' => $v['phone'],
                'bank_name' => $v['bank_name'],
                'card_no' => $v['card_no'],
                'is_default' => $v['is_default'],
                'default' => $v['is_default'] ? '是' : '否',
                'addtime' => $v['addtime'],
            ];
        }
        return $this->toback(0, '', $arys, $total);
    }

    //卡号默认
    public function bankDefaultModify($id)
    {
        $res = (array) $this->dbConn($this->dbUserWithdrawInfo)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return $this->toback(-2, '没有记录');
        }
        //取消默认
        $this->dbConn($this->dbUserWithdrawInfo)
            ->where('uid', $res['uid'])
            ->update(['is_default' => 0]);
        //设置默认
        $this->dbConn($this->dbUserWithdrawInfo)
            ->where('id', $id)
            ->update(['is_default' => 1]);
        return $this->toback();
    }

    //卡号默认初始化
    public function bankDefaultInit($uid)
    {
        $total = $this->dbConn($this->dbUserWithdrawInfo)
            ->where('del', 0)
            ->where('uid', $uid)
            ->count();
        if ($total == 0) {
            return false;
        }
        if ($total > 1) {
            return true;
        }
        $this->dbConn($this->dbUserWithdrawInfo)
            ->where('del', 0)
            ->where('uid', $uid)
            ->update(['is_default' => 1]);
        return true;
    }

    //提现审核列表
    public function txAuthList($pages)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = $this->dbConn($this->dbUserWithdraw)
            ->where('del', 0)
            ->where('status', 1);
        $total = $db->count();
        $res = $db->skip($start)->take($pages['limit'])
            ->orderBy('id', 'desc')
            ->get();
        if (!count($res)) {
            return $this->toback(-2, '没有记录');
        }
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $uOne = (array) $this->dbConn($this->dbUser)
                ->where('del', 0)
                ->where('id', $v['uid'])
                ->first();
            $uname = !empty($uOne)&&$uOne['nickname'] ? $uOne['nickname'] : '-';
            $phone = !empty($uOne)&&$uOne['phone'] ? $uOne['phone'] : '-';
            $status_name = '审核中';
            if ($v['status'] > 1) {
                $status_name = $v['status']==2 ? '已提现' : '提现失败';
            }
            //账号
            $bank_info = '-';
            $bankOne = (array) $this->dbConn($this->dbUserWithdrawInfo)
                ->where('del', 0)
                ->where('uid', $v['uid'])
                ->where('is_default', 1)
                ->first();
            if (!empty($bankOne)) {
                $bank_info = $bankOne['bank_name'].'：'.$bankOne['card_no'];
            }
            $arys[] = [
                'id' => $v['id'],
                'uid' => $v['uid'],
                'uname' => $uname,
                'phone' => $phone,
                'amount' => toNumber($v['amount']),
                'bank_info' => $bank_info,
                'status' => $v['status'],
                'status_name' => $status_name,
                'addtime' => $v['addtime'],
            ];
        }
        return $this->toback(0, '', $arys, $total);
    }

    //提现审核动作
    public function txAuthModify($id, $auth)
    {
        $res = (array) $this->dbConn($this->dbUserWithdraw)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return $this->toback(-2, '没有记录');
        }
        if ($res['status'] == 2) {
            return $this->toback(-2, '已提现');
        }
        if ($res['status'] == 3) {
            return $this->toback(-2, '已拒绝');
        }
        $auth = $auth==1 ? 3 : 2;
        $up = $this->dbConn($this->dbUserWithdraw)->where('id', $id)
            ->update(['status' => $auth, 'approvetime' => toDate()]);
        if (!$up) {
            return $this->toback(-1, 'error');
        }
        return $this->toback();
    }

    /**
     * 设置折扣率
     * @param int $id
     * @param array $pas
     */
    public function modify($id, $pas)
    {
        if ($id) {
            $uOne = (array) $this->dbConn($this->dbUser)
                ->where('del', 0)
                ->where('id', $id)
                ->first();
            if (empty($uOne)) {
                return $this->toback(-2, '该用户不存在');
            }
            $pas['lasttime'] = $pas['uptime'] = toDate();
            $up = $this->dbConn($this->dbUser)->where('id', $id)->update($pas);
            if (!$up) {
                return $this->toback(-1, 'error');
            }
        } else {
            $uOne = (array) $this->dbConn($this->dbUser)
                ->where('del', 0)
                ->where('nickname', $pas['nickname'])
                ->first();
            if (!empty($uOne)) {
                return $this->toback(-2, '该昵称已存在');
            }
            if ($pas['phone']) {
                $uOne = (array) $this->dbConn($this->dbUser)
                    ->where('del', 0)
                    ->where('phone', $pas['phone'])
                    ->first();
                if (!empty($uOne)) {
                    return $this->toback(-2, '该手机号已存在');
                }
            }
            $pas['lasttime'] = $pas['uptime'] = $pas['addtime'] = toDate();
            $up = $this->dbConn($this->dbUser)->insertGetId($pas);
            if (!$up) {
                return $this->toback(-1, 'error');
            }
        }
        return $this->toback();
    }

    /**
     * 分销列表
     * @param array $pages【start，limit】
     * @param int $uid
     */
    public function fxlist($pages, $uid)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = $this->dbConn($this->dbUserIncome)
            ->where('del', 0)
            ->where('uid', $uid);
        $total = $db->count();
        $res = $db->skip($start)->take($pages['limit'])
            ->orderBy('id', 'desc')
            ->get();
        if (!count($res)) {
            return $this->toback(-2, '没有记录');
        }
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $orderOne = (array) $this->dbConn($this->dbOrder)
                ->where('orderno', $v['orderno'])
                ->first();
            $uid = !empty($orderOne)&&$orderOne['uid'] ? $orderOne['uid'] : 0;
            $uOne = (array) $this->dbConn($this->dbUser)
                ->where('id', $uid)
                ->first();
            $arys[] = [
                'id' => $v['id'],
                'uname' => !empty($uOne)&&$uOne['nickname'] ? $uOne['nickname'] : '-',
                'amount' => toNumber($v['amount']),
                'addtime' => $v['addtime'],
            ];
        }
        return $this->toback(0, '', $arys, $total);
    }
    public function getUserLevel($level_id)
    {
        return DB::table($this->dbUlevel)->where('id', $level_id)->value('title');
    }
}